import { defineStore } from 'pinia';

interface CartItem {
  id: string;
  name: string;
  price: number;
  image: string;
  quantity: number;
  selected: boolean;
}

interface CartState {
  items: CartItem[];
}

export const useCartStore = defineStore('cart', {
  state: (): CartState => ({
    items: uni.getStorageSync('cart_items') || []
  }),

  getters: {
    // 总数量
    totalQuantity(): number {
      return this.items.reduce((total, item) => total + item.quantity, 0);
    },

    // 选中的商品总价
    totalPrice(): number {
      return this.items
        .filter(item => item.selected)
        .reduce((total, item) => total + item.price * item.quantity, 0);
    },

    // 是否全选
    isAllSelected(): boolean {
      return this.items.length > 0 && this.items.every(item => item.selected);
    }
  },

  actions: {
    // 添加到购物车
    addToCart(item: Omit<CartItem, 'quantity' | 'selected'>) {
      const existingItem = this.items.find(i => i.id === item.id);
      
      if (existingItem) {
        existingItem.quantity++;
      } else {
        this.items.push({
          ...item,
          quantity: 1,
          selected: true
        });
      }
      
      this.saveToStorage();
    },

    // 从购物车移除
    removeFromCart(id: string) {
      const index = this.items.findIndex(item => item.id === id);
      if (index > -1) {
        this.items.splice(index, 1);
        this.saveToStorage();
      }
    },

    // 更新商品数量
    updateQuantity(id: string, quantity: number) {
      const item = this.items.find(item => item.id === id);
      if (item) {
        item.quantity = Math.max(1, quantity);
        this.saveToStorage();
      }
    },

    // 切换商品选中状态
    toggleSelected(id: string) {
      const item = this.items.find(item => item.id === id);
      if (item) {
        item.selected = !item.selected;
        this.saveToStorage();
      }
    },

    // 全选/取消全选
    toggleAllSelected() {
      const newSelected = !this.isAllSelected;
      this.items.forEach(item => {
        item.selected = newSelected;
      });
      this.saveToStorage();
    },

    // 清空购物车
    clearCart() {
      this.items = [];
      this.saveToStorage();
    },

    // 保存到本地存储
    saveToStorage() {
      uni.setStorageSync('cart_items', this.items);
    }
  }
}); 